package com.zhouyu.proxy;

import com.zhouyu.common.Invocation;
import com.zhouyu.common.URL;
import com.zhouyu.loadbalance.Loadbalance;
import com.zhouyu.protocol.HttpClient;
import com.zhouyu.register.MapRemoteRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class ProxyFactory {

    // 获取代理对象
    public static <T> T getProxy(Class interfaceClass) {
        // 用户配置

        // 创建代理对象
        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                // 创建调用对象
                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);

                // 创建HttpClient对象
                HttpClient httpClient = new HttpClient();

                // 服务发现-获取服务列表
                List<URL> list = MapRemoteRegister.get(interfaceClass.getName());

                // 负载均衡-随机选择一个服务
                URL url = Loadbalance.random(list);

                // 服务调用-发送请求并获取结果
                String result = null;
                try {
                    result = httpClient.send(url.getHostname(), url.getPort(), invocation);
                } catch (Exception e) {
                    return "报错了";
                }
                return result;

            }
        });

        return (T) proxyInstance;
    }
}
